openerp.account_bank_reconciliation_ext = function (instance) {

    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;

    instance.web.account = instance.web.account || {};

    instance.web.account.bankStatementReconciliation.include({
        //重写此方法,添加部分自定义的业务需求逻辑
        start: function() {
            //此处不继承,直接重写
            //this._super();
            var self = this;
            // Retreive statement infos and reconciliation data from the model
            var lines_filter = [['journal_entry_id', '=', false], ['account_id', '=', false]];
            var deferred_promises = [];

            // Working on specified statement(s)
            if (self.statement_ids && self.statement_ids.length > 0) {
                lines_filter.push(['statement_id', 'in', self.statement_ids]);

                // If only one statement, display its name as title and allow to modify it
                if (self.single_statement) {
                    deferred_promises.push(self.model_bank_statement
                        .query(["name"])
                        .filter([['id', '=', self.statement_ids[0]]])
                        .first()
                        .then(function(title){
                            self.title = title.name;
                        })
                    );
                }
                // Anyway, find out how many statement lines are reconciled (for the progressbar)
                deferred_promises.push(self.model_bank_statement
                    .call("number_of_lines_reconciled", [self.statement_ids])
                    .then(function(num) {
                        self.already_reconciled_lines = num;
                    })
                );
            }

            // Get operation templates
            deferred_promises.push(new instance.web.Model("account.statement.operation.template")
                .query(['id','name','account_id','label','amount_type','amount','tax_id','analytic_account_id'])
                .all().then(function (data) {
                    _(data).each(function(preset){
                        self.presets[preset.id] = preset;
                    });
                })
            );

            // Get the function to format currencies
            deferred_promises.push(new instance.web.Model("res.currency")
                .call("get_format_currencies_js_function")
                .then(function(data) {
                    self.formatCurrency = new Function("amount, currency_id", data);
                })
            );

            // Get the function to compare monetary values
            deferred_promises.push(new instance.web.Model("decimal.precision")
                .call("precision_get", ["Account"])
                .then(function(digits) {
                    self.monetaryIsZero = _.partial(instance.web.float_is_zero, _, digits);
                })
            );

            // Get statement lines
            deferred_promises.push(self.model_bank_statement_line
                .query(['id'])
                .filter(lines_filter)
                .all().then(function (data) {
                    self.st_lines = _(data).map(function(o){ return o.id });
                })
            );

            // When queries are done, render template and reconciliation lines
            return $.when.apply($, deferred_promises).then(function(){

                // If there is no statement line to reconcile, stop here
                if (self.st_lines.length === 0) {
                    self.$el.prepend(QWeb.render("bank_statement_nothing_to_reconcile"));
                    return;
                }

                // Create a dict account id -> account code for display facilities
                new instance.web.Model("account.account")
                    .query(['id', 'code'])
                    .all().then(function(data) {
                        _.each(data, function(o) { self.map_account_id_code[o.id] = o.code });
                    });

                // Create a dict currency id -> rounding factor
                new instance.web.Model("res.currency")
                    .query(['id', 'rounding'])
                    .all().then(function(data) {
                        _.each(data, function(o) { self.map_currency_id_rounding[o.id] = o.rounding });
                    });

                new instance.web.Model("ir.model.data")
                    .call("xmlid_to_res_id", ["account.menu_bank_reconcile_bank_statements"])
                    .then(function(data) {
                        self.reconciliation_menu_id = data;
                        self.doReloadMenuReconciliation();
                    });

                // Bind keyboard events TODO : méthode standard ?
                $("body").on("keypress", function (e) {
                    self.keyboardShortcutsHandler(e);
                });

                // Render and display
                self.$el.prepend(QWeb.render("bank_statement_reconciliation", {
                    title: self.title,
                    single_statement: self.single_statement,
                    total_lines: self.already_reconciled_lines+self.st_lines.length
                }));
                self.updateProgressbar();
                var reconciliations_to_show = self.st_lines.slice(0, self.num_reconciliations_fetched_in_batch);
                self.last_displayed_reconciliation_index = reconciliations_to_show.length;
                self.$(".reconciliation_lines_container").css("opacity", 0);

                //添加返回对账单form界面的响应事件
                self.$("#back_to_statement_form_btn").click(function() {
                        self.goBackToStatementsTreeView();
                    });

                //如果安装了收藏模块,添加收藏功能的支持
                if(instance.web_shortcuts){
                    self.shortcut_check();
                }

                // Display the reconciliations
                return self.model_bank_statement_line
                    .call("get_data_for_reconciliations", [reconciliations_to_show], {context:self.session.user_context})
                    .then(function (data) {
                        var child_promises = [];
                        while ((datum = data.shift()) !== undefined)
                            child_promises.push(self.displayReconciliation(datum.st_line.id, 'inactive', false, true, datum.st_line, datum.reconciliation_proposition));
                        $.when.apply($, child_promises).then(function(){
                            self.$(".reconciliation_lines_container").animate({opacity: 1}, self.aestetic_animation_speed);
                            //设置此处初始化的时候,不去加载匹配的模式
                            //self.getChildren()[0].set("mode", "match");
                            //如果对账单行选择了业务伙伴,则第一条记录的对方科目展开并自动匹配;否则不自动展开
                            if(self.getChildren()[0].partner_id){
                                self.getChildren()[0].set("mode", "match");
                            }else{
                                self.getChildren()[0].set("mode", "inactive");
                            }
                            self.updateShowMoreButton();
                        });
                    });
            });
        },

        //收藏按钮的点击功能注册,响应事件
        shortcut_check : function() {
            var self = this;
            var shortcuts_menu = instance.webclient.user_menu.shortcuts;
            var grandparent = this.getParent() && this.getParent().getParent();
            // display shortcuts if on the first view for the action
            var $shortcut_toggle = this.$el.find('.oe_shortcuts_toggle');

            // Anonymous users don't have user_menu
            if (shortcuts_menu) {
                $shortcut_toggle.toggleClass('oe_shortcuts_remove', shortcuts_menu.has(self.session.active_id));
                $shortcut_toggle.unbind("click").click(function() {
                    if ($shortcut_toggle.hasClass("oe_shortcuts_remove")) {
                        shortcuts_menu.trigger('remove', self.session.active_id);
                    } else {
                        shortcuts_menu.trigger('add', {
                            'user_id': self.session.uid,
                            'menu_id': self.session.active_id,
                            'name': 'action_bank_reconcile_bank_statements'
                        });
                    }
                    $shortcut_toggle.toggleClass("oe_shortcuts_remove");
                });
            }
        },

        //处理完核销操作之后,返回原来的form界面,而不是tree界面
        goBackToStatementsTreeView: function() {
            var self = this;
            new instance.web.Model("ir.model.data")
                .call("get_object_reference", ['account', 'action_bank_statement_form_bank'])
                .then(function (result) {
                    var action_id = result[1];
                    var action_manager = self.getParent();
                    var breadcrumbs = action_manager.breadcrumbs;
                    var found = false;
                    for (var i=breadcrumbs.length-1; i>=0; i--) {
                        if (breadcrumbs[i].action && breadcrumbs[i].action.id === action_id) {
                            var title = breadcrumbs[i].get_title();
                            action_manager.select_breadcrumb(i, _.isArray(title) ? i : undefined);
                            found = true;
                        }
                    }
                    if (!found)
                        self.do_action('history_back');
                });
        }
    });

    instance.web.account.bankStatementReconciliationLine.include({
        //扩展银行对账单行的列表头展示
        updateMatchView: function() {
            var self = this;
            this._super.apply(this, arguments);
            var tbody = self.$(".match table tbody");
            var $thead = $(QWeb.render("bank_statement_reconciliation_line_thead"));
            //添加列表头到table下的tbody之前
            $thead.insertBefore(tbody);
        }
    });
};


